package com.interview.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.interview.Mapper.RoleMapper;
import com.interview.Mapper.UserMapper;
import com.interview.Mapper.UserRoleMapper;
import com.interview.pojo.LoginDto;
import com.interview.pojo.User;
import com.interview.pojo.UserRole;
import com.interview.service.UserService;
import com.itheima.common.util.AppJwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import static com.interview.UserApplication.tokenMap;
import static com.interview.UserApplication.userRoleMap;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;


    @Override
    public Map<String, Object> login(LoginDto loginDto) throws Exception {
        //1.先通过手机号 获取到用户信息
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        queryWrapper.eq("username",loginDto.getUsername());
        User user = userMapper.selectOne(queryWrapper);
        //2.判断是否存在，如果不存在  抛出自定义的异常   手机号或者密码错误
        if(user==null){
            throw new Exception("用户名或者密码错误");
        }
        System.out.println("4");

        //3.获取数据库中的密码
        String passwordfromDb = user.getPassword();


        //5.判断 数据库的中密码和当前密文是否一致 如果不一致 抛出自定义的异常   手机号或者密码错误
        if(!passwordfromDb.equals(passwordfromDb)){
            throw new Exception("用户名或者密码错误");
        }
        //6.生成令牌 （包括令牌信息 和用户的信息（密码去掉） 返回）
        String token = AppJwtUtil.createToken(Long.valueOf(user.getId()));
        HashMap<String, Object> info = new HashMap<>();
        info.put("token",token);
        user.setPassword("");
        info.put("user",user);

        //7.把令牌和权限存放在map中
        tokenMap.put(token,user.getId());

        LambdaQueryWrapper<UserRole> userRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        UserRole userRole = new UserRole();
        userRole.setUserId(user.getId());
        userRoleLambdaQueryWrapper.setEntity(userRole);
        List<UserRole> userRoles = userRoleMapper.selectList(userRoleLambdaQueryWrapper);
        HashSet<String> roleStr = new HashSet<>();
        for (UserRole userRole1 : userRoles) {
            roleStr.add(userRole1.getRoleName());
        }
        userRoleMap.put(user.getId().toString(),roleStr);

        return info;
    }
}
